package com.example.exampleproject.base.exception;

import android.net.ParseException;

import com.example.exampleproject.App;
import com.example.exampleproject.R;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;

import java.io.InterruptedIOException;
import java.io.NotSerializableException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import retrofit2.HttpException;

public class ApiException extends Exception{
    private String mMessage;

    private ApiException(Throwable throwable) {
        this(throwable, throwable.getMessage());
    }

    private ApiException(Throwable throwable, int messageRes) {
        this(throwable, App.getApp().getResources().getString(messageRes));
    }

    private ApiException(Throwable throwable, String message) {
        super(throwable);
        this.mMessage = message;
    }

    public static ApiException handleException(Throwable e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            return new ApiException(httpException, httpException.getMessage());
        } else if (e instanceof JsonSyntaxException) {
            return new ApiException(e, R.string.exception_server);
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof JsonSerializer || e instanceof NotSerializableException || e instanceof ParseException) {
            return new ApiException(e, R.string.exception_json_parse);
        } else if (e instanceof ClassCastException) {
            return new ApiException(e, R.string.exception_class_cast);
        } else if (e instanceof ConnectException) {
            return new ApiException(e, R.string.exception_connect);
        } else if (e instanceof SSLHandshakeException) {
            return new ApiException(e, R.string.exception_ssl_handshake);
        } else if (e instanceof ConnectTimeoutException || e instanceof SocketTimeoutException) {
            return new ApiException(e, R.string.exception_connect_timeout);
        } else if (e instanceof InterruptedIOException) {
            return new ApiException(e, R.string.exception_interrupted_io);
        } else if (e instanceof UnknownHostException) {
            return new ApiException(e, R.string.exception_unknown_host);
        } else if (e instanceof NullPointerException) {
            return new ApiException(e, R.string.exception_null_printer);
        } else {
            return new ApiException(e, R.string.exception_unknown);
        }
    }

    @Override
    public String getMessage() {
        return mMessage;
    }

}
